import {
  addItemToCart,
  fetchCartInfo,
  modifyCartItemNum,
  modifyCartItemSelected,
  removeCartItem
} from "@a/cart";
import { Toast } from 'antd-mobile';
export default {
  // 命名空间
  namespace: 'cart',
  // 存储的数据
  state: {
    // 购物车数据
    items: [],
    // 购物车商品总价格
    total: 0,
    // 购物车总数量
    number: 0
  },
  // 修改 state 的值
  reducers: {
    // 给购物车数据赋值
    initCart(state: any, action: any) {
      state.items = action.data.items;
      state.total = action.data.price;
      state.number = action.data.number
      return {
        ...state
      }
    },
  },
  effects: {
    // 加入购物车
    *addCart(action: any, { put, call }: any) {
      // 调用请求
      const res = yield call(addItemToCart, action.data);
      if (res.data.code === 0) {
        // 触发reducer
        Toast.show({ content: '加入购物车成功' })
        yield put({ type: 'initCart', data: res.data.data })
      }
    },
    // 获取购物车数据
    *getItensInfo(action: any, { put, call }: any) {
      // 调用请求
      const res = yield call(fetchCartInfo);
      if (res.data.code === 0) {
        yield put({ type: 'initCart', data: res.data.data })
      }
    },
    // 购物车修改购买数量
    *modCartNumber(action: any, { put, call }: any) {
      const res = yield call(modifyCartItemNum, action.data);
      if (res.data.code === 0) {
        Toast.show({ content: '修改成功' })
        yield put({ type: 'initCart', data: res.data.data })
      }
    },
    //移除购物车中某条记录
    *delCartItems(action: any, { put, call }: any) {
      const res = yield call(removeCartItem, action.data);
      if (res.data.code === 0) {
        Toast.show({ content: '删除成功' })
        yield put({ type: 'initCart', data: res.data.data })
      }
      if (res.data.code === 700) {
        yield put({
          type: 'initCart', data: {
            items: [],
            price: 0,
            number: 0
          }
        });
      }
    },
    //购物车修改选中状态
    *modCartSelected(action: any, { put, call }: any) {
      const res = yield call(modifyCartItemSelected, action.data);
      if (res.data.code === 0) {
        Toast.show({ content: '修改成功' })
        yield put({ type: 'initCart', data: res.data.data })
      }
    },
  },
};
